package com.lancoo.answer.widget.combinationView;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.lancoo.answer.R;
import com.lancoo.answer.model.AnswerConstant;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.util.ExamFontSizeAdjustUtils;
import com.lancoo.answer.util.RichTxtDealTuils;

import java.util.List;

/**
 * Created by pengmi on 2021/12/7 20:42
 * Description:作文题作答选项切换组合view
 */
public class CompositionQueseView extends RelativeLayout implements View.OnClickListener {

    private static final String TAG = "CompositionQueseView";
    private TextView tv_queseBody;
    private long subTime;
    private int currentAnswerType=0;//作答方式 0-文本 1-音频，2-图片，3-视频
    private final String SP_NAME="sp_exame";
    private final String KEY_ALEART_AGAIN="key_aleart_again";
    private Item item;
    private OnAnswerTypeChangeCallback onAnswerTypeChangeCallback;
    private boolean isCloseAudioAnswer,isCloseVideoAnswer,isCloseTxtAnswer,isCloseImgAnswer;


    public CompositionQueseView(Context context) {
        super(context);
        init(context);
    }

    public CompositionQueseView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CompositionQueseView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }


    private void init(Context context){
        Log.e(TAG,"init view");
        LayoutInflater.from(context).inflate(R.layout.ev_layout_composition,this);
        tv_queseBody = findViewById(R.id.tv_quese_body);
        adjustFontSize();
    }


    public void intData(Child child){
        Log.e(TAG,"intData child");
        if(child==null){
            Log.e(TAG,"child is null");
            return;
        }
        List<Item> itemList = child.getItemList();
        if(itemList==null){
            return;
        }
        item = itemList.get(Math.min(child.getSelectedItemIndex(),child.getItemList().size()-1));

        SpannableStringBuilder ssb_childBody=new SpannableStringBuilder();
        ssb_childBody.append(RichTxtDealTuils.addMarkTagImg(getContext(),item));
        ssb_childBody.append(String.format("%s.", item.getSortIndex()));
        tv_queseBody.setText(ssb_childBody);
        if(TextUtils.isEmpty(item.getSortIndex())){
            tv_queseBody.setVisibility(GONE);
        }
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean!=null&&taskControlBean.getEnableAnwer()==0){//禁止作答
            findViewById(R.id.img_pencil).setEnabled(false);
            findViewById(R.id.img_photograph).setEnabled(false);
            findViewById(R.id.img_microphone).setEnabled(false);
            findViewById(R.id.img_video).setEnabled(false);
        }
        findViewById(R.id.img_pencil).setOnClickListener(this);
        findViewById(R.id.img_photograph).setOnClickListener(this);
        findViewById(R.id.img_microphone).setOnClickListener(this);
        findViewById(R.id.img_video).setOnClickListener(this);
        findViewById(R.id.img_video).setVisibility(isCloseVideoAnswer?GONE:VISIBLE);
        findViewById(R.id.img_microphone).setVisibility(isCloseAudioAnswer?GONE:VISIBLE);
        findViewById(R.id.img_pencil).setVisibility(isCloseTxtAnswer?GONE:VISIBLE);
        findViewById(R.id.img_photograph).setVisibility(isCloseImgAnswer?GONE:VISIBLE);
        if(isCloseTxtAnswer){
            ImageView img_microphone = findViewById(R.id.img_microphone);
            img_microphone.setImageResource(R.drawable.ev_vector_pencil);

        }
        Log.e("aaaa","之前i："+item.getWrittingAnswerType());
        if(item.getWrittingAnswerType()==0&&isCloseTxtAnswer){
            item.setWrittingAnswerType(1);
        }
        Log.e("aaaa","当前答题点answerType："+item.getWrittingAnswerType());
        switch (item.getWrittingAnswerType()){
            case AnswerConstant.ANSWER_TYPE_TXT_AUDIO:
                findViewById(R.id.img_microphone).setSelected(true);
                currentAnswerType=1;
                break;
            case AnswerConstant.ANSWER_TYPE_PICTURE:
                findViewById(R.id.img_photograph).setSelected(true);
                currentAnswerType=2;
                break;
            case AnswerConstant.ANSWER_TYPE_VIDEO:
                findViewById(R.id.img_video).setSelected(true);
                currentAnswerType=3;
                break;
            default:
                if(isCloseTxtAnswer){
                    findViewById(R.id.img_microphone).setSelected(true);
                    currentAnswerType=1;
                    item.setWrittingAnswerType(AnswerConstant.ANSWER_TYPE_TXT_AUDIO);
                }else{
                    findViewById(R.id.img_pencil).setSelected(true);
                    currentAnswerType=0;
                }

        }
        if(onAnswerTypeChangeCallback!=null){
            onAnswerTypeChangeCallback.onAnswerTypeSelected(currentAnswerType);
        }

    }

    @Override
    public void onClick(View v) {

        if(System.currentTimeMillis()-subTime<200){
            return;
        }
        subTime=System.currentTimeMillis();
        int id = v.getId();
        if(id==R.id.img_pencil){
            showSwitchAnswerTypeDialog(0);
        }else if(id==R.id.img_microphone){
            showSwitchAnswerTypeDialog(1);
        }else if(id==R.id.img_photograph){
            showSwitchAnswerTypeDialog(2);
        }else if(id==R.id.img_video){
            showSwitchAnswerTypeDialog(3);
        }
    }


    private void switchAnswerType(int answerType){
        findViewById(R.id.img_pencil).setSelected(answerType==0);
        findViewById(R.id.img_microphone).setSelected(answerType==1);
        findViewById(R.id.img_photograph).setSelected(answerType==2);
        findViewById(R.id.img_video).setSelected(answerType==3);
        currentAnswerType=answerType;
        switch (answerType){
            case 1:
                item.setWrittingAnswerType(AnswerConstant.ANSWER_TYPE_TXT_AUDIO);  //文本+语音
                break;
            case 2:
                item.setWrittingAnswerType(AnswerConstant.ANSWER_TYPE_PICTURE);  //图片
                break;
            case 3:
                item.setWrittingAnswerType(AnswerConstant.ANSWER_TYPE_VIDEO);  //视频
                break;
            default:
                item.setWrittingAnswerType(AnswerConstant.ANSWER_TYPE_TXT);  //纯文本
        }
        if(onAnswerTypeChangeCallback!=null){
            onAnswerTypeChangeCallback.onAnswerTypeSelected(answerType);
        }
    }

    private void showSwitchAnswerTypeDialog(final int answerType){
        if(currentAnswerType==answerType||getContext()==null){
            return;
        }
        SharedPreferences sp=getContext().getSharedPreferences(SP_NAME,Context.MODE_PRIVATE);
        boolean isAgain=sp.getBoolean(KEY_ALEART_AGAIN,false);
        if(isAgain){
            switchAnswerType(answerType);
            return;
        }
        View inflate=LayoutInflater.from(getContext()).inflate(R.layout.ev_dialog_switch_answer_type,null);
        AlertDialog.Builder builder=new AlertDialog.Builder(getContext(),R.style.ev_dialogStyle);
        builder.setView(inflate);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        WindowManager.LayoutParams attributes = window.getAttributes();
        int width =getContext().getResources().getDisplayMetrics().widthPixels;
        attributes.width=Math.min(width*3/4,width*3/4);
        alertDialog.getWindow().setAttributes(attributes);

        inflate.findViewById(R.id.tv_cancel).setOnClickListener(v -> {
            if(System.currentTimeMillis()-subTime<200){
                return;
            }
            subTime=System.currentTimeMillis();
            alertDialog.dismiss();
            SharedPreferences sp1 =getContext().getSharedPreferences(SP_NAME,Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sp1.edit();
            edit.putBoolean(KEY_ALEART_AGAIN,true);
            edit.apply();
            switchAnswerType(answerType);
        });
        inflate.findViewById(R.id.tv_sure).setOnClickListener(v -> {
            if(System.currentTimeMillis()-subTime<200){
                return;
            }
            subTime=System.currentTimeMillis();
            alertDialog.dismiss();
            switchAnswerType(answerType);
        });

    }




    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        Log.e(TAG,"onDetachedFromWindow");
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
        Log.e(TAG,"onWindowFocusChanged:"+hasWindowFocus);
    }


    public void setOnAnswerTypeChangeCallback(OnAnswerTypeChangeCallback onCallBack){
        this.onAnswerTypeChangeCallback=onCallBack;
    }

    public void setCloseAudioAnswer(boolean isCloseAudioAnswer){
        this.isCloseAudioAnswer=isCloseAudioAnswer;
    }

    public void setCloseVideoAnswer(boolean isCloseVideoAnswer){
        this.isCloseVideoAnswer=isCloseVideoAnswer;
    }

    public void setCloseTxtAnswer(boolean isCloseTxtAnswer){
        this.isCloseTxtAnswer=isCloseTxtAnswer;
    }

    public void setCloseImgAnswer(boolean closeImgAnswer) {
        isCloseImgAnswer = closeImgAnswer;
    }

    public abstract static class OnAnswerTypeChangeCallback {

        public void onAnswerTypeSelected(int position) {
        }

    }

    public void hideSortIndex(){
        if(tv_queseBody==null){
            return;
        }
        tv_queseBody.setVisibility(INVISIBLE);
    }


    public void adjustFontSize(){
        if(tv_queseBody==null){
            return;
        }
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(tv_queseBody,15);
    }

    public void markQuestion(){
        if(tv_queseBody==null||item==null){
            return;
        }
        boolean itemMark = item.getItemMark();
        item.setItemMark(!itemMark);
        SpannableStringBuilder ssb_childBody=new SpannableStringBuilder();
        ssb_childBody.append(RichTxtDealTuils.addMarkTagImg(getContext(),item));
        ssb_childBody.append(String.format("%s.", item.getSortIndex()));
        tv_queseBody.setText(ssb_childBody);
    }


}
